import {getUploadParams} from '@/api/common/index.js'
import {TokenKey,LocalUserInfoKey,ApiHost} from '@/config/index.js' 

import store from '@/store/index.js'

export function uploadFile(filePath,type,onProgress){
	return new Promise(async (resolve,reject)=>{
		let uploadParams=await getUploadParams();
		let randomStr=+Math.floor(Math.random() * 100)
		let userInfo=store.state.user.userInfo
		if(userInfo){
			randomStr=String(userInfo.id)+"/"+randomStr
		}
		let key = uploadParams.data.key  + randomStr +'/'+new Date().getTime()+ `.${type}`
		let formData = {
			key: key,
			policy: uploadParams.data.policy,
			OSSAccessKeyId: uploadParams.data.accessid,
			success_action_status: 200,
			signature: uploadParams.data.signature
		};
		var uploadTask =uni.uploadFile({
			url:uploadParams.data.host,
			filePath,
			name:'file',
			formData,
			timeout:1000*60*5,
			header:{
				[TokenKey]:uni.getStorageSync(TokenKey)
			},
			
			success(res){
				uni.hideLoading()
				resolve('/'+key)
			},
			fail(e){
				console.log(e)
				uni.hideLoading()
				reject()
			}
		})
		uploadTask.onProgressUpdate((res)=>{
			if(onProgress){
				onProgress(res.progress)
			}
		})
	})
}


export  function uploadIdCardForLL() {
 let _this = this
 return new Promise((resolve, reject) => {
  uni.chooseImage({
   count: 1,
   fileType: 'image',
   success(ress) {
    uni.showLoading({
     title: '上传中...',
     mask: true
    })
    uni.uploadFile({
     url: ApiHost + '/api/order/ll/uploadToLianLian',
     filePath: ress.tempFilePaths[0],
     name: 'file',
     // formData: formData,
     header: {
      // #ifdef MP
      "Content-Type": "multipart/form-data",
      // #endif
      "token": uni.getStorageSync('token')
     },
     success: function(res) {
      uni.hideLoading();
      if (res.statusCode == 200) {
       let successData = JSON.parse(res.data)
       successData.data.url = ress.tempFilePaths[0]
       if (successData.code == 1) {
        resolve(successData.data)
       } else {
        uni.showToast({
         title: successData.msg,
         icon: "none"
        })
        reject(successData.data)
       }
      } else {
       uni.showToast({
        title: res.errMsg,
        icon: "none"
       })
      }
     },
     fail: function(res) {
      uni.hideLoading();
      uni.showToast({
       title: res.errMsg,
       icon: "none"
      })
     }
    })
   }
  })
 })
}